#include "gui_bridge.h"

#include <QDebug>
#include <QMetaObject> // 为了线程安全使用invokeMethod

// GuiSignaler单例实现
GuiSignaler *GuiSignaler::s_instance = nullptr;

GuiSignaler *GuiSignaler::instance()
{
    if (!s_instance)
    {
        s_instance = new GuiSignaler();
    }
    return s_instance;
}

GuiSignaler::GuiSignaler(QObject *parent) : QObject(parent)
{
    // 构造函数
}

// Signal emitter methods
void GuiSignaler::emitLoginResult(bool success, const QString &message)
{
    emit loginResultReceived(success, message);
}

void GuiSignaler::emitFileListUpdated(const QList<FileItem> &files)
{
    emit fileListUpdated(files);
}

void GuiSignaler::emitLogMessage(const QString &message, bool isError)
{
    emit logMessageReceived(message, isError);
}

void GuiSignaler::emitTransferProgress(const QString &filename, int percentage, const QString &status)
{
    emit transferProgressUpdated(filename, percentage, status);
}

void GuiSignaler::emitTransferCompleted(const QString &filename, bool success, const QString &message)
{
    emit transferCompleted(filename, success, message);
}

// New slot implementation for GuiSignaler
void GuiSignaler::emitRegistrationResult(bool success, const QString &message)
{
    emit registrationResultCb(success, message);
}

// New slot implementation for GuiSignaler for delete result
void GuiSignaler::emitDeleteResult(bool success, const QString &filename, const QString &message)
{
    emit deleteResultCb(success, filename, message);
}

// --- C函数实现 ---

extern "C"
{

    // 当C代码调用这些函数时，它们将转换数据并触发Qt信号

    void sfts_ui_on_login_result(int success, const char *username_or_error_message)
    {
        qDebug() << "[BRIDGE] sfts_ui_on_login_result called: Success=" << success
                 << ", Message=" << username_or_error_message;

        // 确保在主线程中发射信号
        QString msg = QString::fromUtf8(username_or_error_message);
        bool success_flag = (success == 1); // 在C层，1表示成功

        // 使用GuiSignaler的方法发射信号
        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitLoginResult",
            Qt::QueuedConnection,
            Q_ARG(bool, success_flag),
            Q_ARG(QString, msg));
    }

    void sfts_ui_on_file_list_updated(sfts_FileListItem_C *items, int count)
    {
        qDebug() << "[BRIDGE] sfts_ui_on_file_list_updated called: Count=" << count;

        // 将C结构转换为Qt结构
        QList<FileItem> fileList;
        for (int i = 0; i < count; ++i)
        {
            FileItem item;
            item.name = QString::fromUtf8(items[i].name);
            item.type = QString::fromUtf8(items[i].type);
            item.size = items[i].size;
            item.permissions = QString::fromUtf8(items[i].permissions);
            item.lastModified = QString::fromUtf8(items[i].lastModified);
            fileList.append(item);
        }

        // 确保在主线程中发射信号
        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitFileListUpdated",
            Qt::QueuedConnection,
            Q_ARG(QList<FileItem>, fileList));
    }

    void sfts_ui_on_log_message(const char *message, int is_error)
    {
        // 避免日志信息过多
        // qDebug() << "[BRIDGE] sfts_ui_on_log_message called: " << message;

        QString msg = QString::fromUtf8(message);
        bool error_flag = (is_error == 1); // 在C层，1表示错误

        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitLogMessage",
            Qt::QueuedConnection,
            Q_ARG(QString, msg),
            Q_ARG(bool, error_flag));
    }

    void sfts_ui_on_transfer_progress(const char *filename, int percentage, const char *status_message)
    {
        // 避免进度信息过多导致日志刷屏
        // qDebug() << "[BRIDGE] Progress update: " << percentage << "%";

        QString fname = QString::fromUtf8(filename);
        QString status = QString::fromUtf8(status_message);

        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitTransferProgress",
            Qt::QueuedConnection,
            Q_ARG(QString, fname),
            Q_ARG(int, percentage),
            Q_ARG(QString, status));
    }

    void sfts_ui_on_transfer_complete(const char *filename, int success, const char *message)
    {
        qDebug() << "[BRIDGE] sfts_ui_on_transfer_complete: "
                 << filename << ", success=" << success << ", message=" << message;

        QString fname = QString::fromUtf8(filename);
        QString msg = QString::fromUtf8(message);
        bool success_flag = (success == 1); // 在C层，1表示成功

        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitTransferCompleted",
            Qt::QueuedConnection,
            Q_ARG(QString, fname),
            Q_ARG(bool, success_flag),
            Q_ARG(QString, msg));
    }

    // New C function implementation
    void sfts_ui_on_registration_result(int success, const char *message)
    {
        qDebug() << "[BRIDGE] sfts_ui_on_registration_result called: Success=" << success
                 << ", Message=" << message;
        QString msg = QString::fromUtf8(message);
        bool success_flag = (success == 1);

        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitRegistrationResult",
            Qt::QueuedConnection,
            Q_ARG(bool, success_flag),
            Q_ARG(QString, msg));
    }

    // New C function implementation for delete result
    void sfts_ui_on_delete_result(int success, const char *filename, const char *message)
    {
        qDebug() << "[BRIDGE] sfts_ui_on_delete_result called: Success=" << success
                 << ", Filename=" << filename << ", Message=" << message;
        QString fname_str = QString::fromUtf8(filename);
        QString msg_str = QString::fromUtf8(message);
        bool success_flag = (success == 1);

        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitDeleteResult", // The public slot name in GuiSignaler
            Qt::QueuedConnection,
            Q_ARG(bool, success_flag),
            Q_ARG(QString, fname_str),
            Q_ARG(QString, msg_str));
    }

    void sfts_ui_on_file_list_error(const char *path, const char *error_message)
    {
        qDebug() << "[BRIDGE] sfts_ui_on_file_list_error called: Path=" << path
                 << ", Error=" << error_message;

        QString formatted_error = QString("Error fetching file list for path '%1': %2").arg(QString::fromUtf8(path)).arg(QString::fromUtf8(error_message));

        QMetaObject::invokeMethod(
            GuiSignaler::instance(),
            "emitLogMessage",
            Qt::QueuedConnection,
            Q_ARG(QString, formatted_error),
            Q_ARG(bool, true) // true indicates it's an error message
        );
    }

} // extern "C"